package com.zygh.lz.securitys;

import com.zygh.lz.entity.Staff;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.service.role.SysUserRoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ms151
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    StaffService sysUserService;
    @Autowired
    SysUserRoleServiceImpl sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Staff sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }
        return new AccountUser(sysUser.getSysStaffId().longValue(), sysUser.getStaffTel(), sysUser.getStaffPassword(), getUserAuthority(sysUser.getSysStaffId().longValue()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     *
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {

        // 角色(ROLE_admin)、菜单操作权限 sys:user:list// ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = sysUserRoleService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }


}
